const utils = {
  //转换时间戳
  formatTimestampToString(timestamp){
   const date = new Date(timestamp)
   const yyyy = date.getFullYear()
   const mm = String(date.getMonth()+1).padStart(2,'0')
   const dd = String(date.getDate()).padStart(2,'0')
   return `${yyyy}-${mm}-${dd}`
  },
  // 生成[min, max]区间内的随机整数
  randomInteger(min, max) {
    // Math.random() // [0, 1)
    // //  min: 5, max: 10
    // Math.random() * (max - min + 1) // [0, 6)
    // Math.floor(Math.random() * (max - min + 1)) // [0, 5]
    // //  + min 的目的 ==> 保证下限
    // Math.floor(Math.random() * (max - min + 1)) + min // [5, 10]
    return Math.floor(Math.random() * (max - min + 1)) + min
  },

  // 获取当前页面
  getCurrentPage() {
    const pages = getCurrentPages()
    return pages[pages.length - 1]
  },

  // 判断是否为tabbar页面
  isTabbar(url) {
    // eslint-disable-next-line no-undef
    return __wxConfig.tabBar.list.some((v) => {
      return v.pagePath.startsWith(url)
    })
  },

  // 重定向至登录页面
  redirectToLogin() {
    const curPage = utils.getCurrentPage()
    const isTabbar = utils.isTabbar(curPage.route)
    const returnType = isTabbar ? 'switchTab' : 'redirectTo'

    // 处理查询参数
    const returnUrlQuery = Object.entries(curPage.options)
      .map(([k, v]) => `${k}=${v}`)
      .join('&')

    // 编码url
    const returnUrl = encodeURIComponent(`/${curPage.route}?${returnUrlQuery}`.replace(/\?$/,''))

    wx.redirectTo({
      // url: '/pages/login/index?returnUrl=%2Fhouse_pkg%2Fpages%2Fform%2Findex%3Ftitle%3D%E7%91%9E%E5%92%8C%E9%B9%BF%E9%B8%A3%E5%BA%9C2%E6%A0%8B2202%E5%AE%A4%26name%3D%E5%BC%A0%E4%B8%89&returnType=switchTab'
      // url: '/pages/login/index?returnUrl=/house_pkg/pages/form/index?title=瑞和鹿鸣府2栋2202室&name=张三&returnType=switchTab'
      url: `/pages/login/index?returnUrl=${returnUrl}&returnType=${returnType}`,
    })
  },

  toast(title = '数据加载失败...') {
    return wx.showToast({
      title,
      mask: true,
      icon: 'none',
    })
  },
}

export default utils

wx.utils = utils
